﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace PicTools
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            SetDefaultLocation();
            this.Icon = global::PicTools.Properties.Resources.icon_main;
            this.myIcon.Icon = global::PicTools.Properties.Resources.icon_main;

            textBox1.Text = ConfigurationManager.AppSettings["sourcePath"];
            textBox2.Text = ConfigurationManager.AppSettings["targetPicPath"];
            textBox3.Text = ConfigurationManager.AppSettings["targetVideoPath"];
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var obj = new Thread(doWork);
            obj.Start();
        }

        #region 开始处理

        /// <summary>
        /// 开始处理
        /// </summary>
        private void doWork()
        {
            var list = GetFiles(textBox1.Text).Where(ex => Path.GetExtension(ex).ToLower() == ".jpg" || Path.GetExtension(ex).ToLower() == ".jpeg" || Path.GetExtension(ex).ToLower() == ".mp4").ToList();

            int i = 0;
            foreach (var item in list)
            {
                var dir = GetTakePicDate(item);
                var fileDir = textBox2.Text + "\\" + dir + "\\";
                if (Path.GetExtension(item).ToLower() == ".mp4")//视频地址
                {
                    fileDir = textBox3.Text + "\\" + dir + "\\";
                }
                if (!Directory.Exists(fileDir))
                {
                    Directory.CreateDirectory(fileDir);
                }
                var targetFile = fileDir + Path.GetFileName(item);

                try
                {
                    Copy(item, targetFile);
                    //CommonLib.LogHelper.AddLog(string.Format("地址:{0} 目标地址:{1}", item, targetFile));
                }
                catch
                {
                    //CommonLib.LogHelper.AddLog(string.Format("存在:地址:{0} 目标地址:{1}", item, targetFile));
                }

                label8.BeginInvoke(new Action(() =>
                {
                    label8.Text = string.Format("{0}/{1}", i, list.Count);
                }));
                i++;
            }
            MessageBox.Show("全部处理完成!");
        }
        #endregion

        #region 浏览

        private void btn_browse1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowDialog();
            textBox1.Text = fbd.SelectedPath;
        }

        private void btn_browse2_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowDialog();
            textBox2.Text = fbd.SelectedPath;
        }
        private void btn_browse3_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowDialog();
            textBox3.Text = fbd.SelectedPath;
        }
        #endregion

        #region 获取Exif中的照片拍摄日期

        /// <summary>
        /// 获取Exif中的照片拍摄日期
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>拍摄日期</returns>
        private string GetTakePicDate(string fileName)
        {
            Encoding ascii = Encoding.ASCII;
            string picDate;

            try
            {
                FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                Image image = Image.FromStream(stream, true, false);

                foreach (PropertyItem p in image.PropertyItems)
                {
                    //获取拍摄日期时间
                    if (p.Id == 0x9003) // 0x0132 最后更新时间
                    {
                        stream.Close();

                        picDate = ascii.GetString(p.Value);
                        if ((!"".Equals(picDate)) && picDate.Length >= 10)
                        {
                            // 拍摄日期
                            picDate = picDate.Substring(0, 7);
                            picDate = picDate.Replace(":", "-");
                            return picDate;
                        }
                    }
                }
                stream.Close();
            }
            catch (Exception)
            {
            }
            FileInfo fi = new FileInfo(fileName);
            return fi.LastWriteTime.ToString("yyyy-MM");
        }
        #endregion

        #region 拷贝文件

        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="targetFileName"></param>
        private void Copy(string fileName, string targetFileName)
        {
            if(File.Exists(targetFileName))
            {
                return;
            }
            lb_fileSoure.BeginInvoke(new Action(() =>
            {
                lb_fileSoure.Text = fileName;
                lb_fileTarget.Text = targetFileName;
            }));

            int WriterByetNub = 1024 * 1024 * 1;//1M复制速度

            var FileToRead = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            var FileToWrite = new FileStream(targetFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            var byteToWrite = new byte[WriterByetNub];

            var WriteTimes = FileToRead.Length / WriterByetNub;//循环次数  

            var L_Size = Convert.ToInt32(FileToRead.Length % WriterByetNub);//多次循环后剩余字节            
            var byteToLastWrite = new byte[L_Size]; //剩余长度

            for (long i = 0; i < WriteTimes; i++)
            {
                //读源文件
                FileToRead.Read(byteToWrite, 0, WriterByetNub);
                //写数据到目标文件
                FileToWrite.Write(byteToWrite, 0, WriterByetNub);
                lb_jd.BeginInvoke(new Action(() =>
                {
                    lb_jd.Text = Math.Round(Convert.ToDecimal((i * 100)) / WriteTimes, 2).ToString() + "%";
                }));
            }

            //剩余字节的读和写
            if (L_Size != 0)
            {
                FileToRead.Read(byteToLastWrite, 0, L_Size);
                FileToWrite.Write(byteToLastWrite, 0, L_Size);
            }

            FileToRead.Flush();
            FileToWrite.Flush();
            FileToRead.Close();
            FileToWrite.Close();
        }
        #endregion

        #region 设置默认位置

        /// <summary>
        /// 默认位置
        /// </summary>
        public void SetDefaultLocation()
        {
            Rectangle rect = new Rectangle();
            rect = Screen.GetWorkingArea(this);

            this.Left = (rect.Width - this.Width) / 2;
            this.Top = (rect.Height - this.Height) / 2;
        }
        #endregion

        #region 关闭到托盘

        private void 显示主窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            WindowState = FormWindowState.Normal;
            this.Focus();
        }

        private void 目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var path = System.AppDomain.CurrentDomain.BaseDirectory;
            System.Diagnostics.Process.Start(path);
        }
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Application.Exit();
        }

        private void myIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.TopMost = true;
                this.Show();
                WindowState = FormWindowState.Normal;
                this.Focus();
                this.TopMost = false;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
            }
        }
        #endregion

        #region 获取目录下所有文件

        /// <summary>
        ///获取目录下所有文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>

        public static List<string> GetFiles(string path)
        {
            var list = new List<string>();
            if (Directory.Exists(path))
            {
                list = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).ToList();
            }
            return list;
        }
        #endregion 
    }
}
